package com.qws.xprinter.flutter_xprinter

import com.qws.xprinter.flutter_xprinter.bean.DeviceType
import com.qws.xprinter.flutter_xprinter.device.GPrinter
import com.qws.xprinter.flutter_xprinter.device.QwsPrinter
import com.qws.xprinter.flutter_xprinter.device.XPrinter
import java.util.concurrent.ConcurrentHashMap

object PrinterManager {
    private var devices: ConcurrentHashMap<String, QwsPrinter> = ConcurrentHashMap()

    fun sendPrintTask(deviceType: Int, connType: Int, address: String, bytes: List<Int>) {
        var printer = devices[address]
        if (printer == null) {
            // 创建新打印机实例
            printer = createPrinter(deviceType, connType, address)
            if (printer != null) {
                devices[address] = printer
            }
        }
        printer?.sendPrintTask(bytes)
    }

    fun connect(deviceType: Int, connType: Int, address: String) {
        var printer = devices[address]
        if (printer == null) {
            printer =  createPrinter(deviceType, connType, address)
            printer?.connect()
            if (printer != null) {
                devices[address] = printer
            }
        } else {
            printer.connect()
        }
    }

    fun disconnect(address: String) {
        val printer = devices[address]
        printer?.disconnect()
    }

    private fun createPrinter(deviceType: Int, connType: Int, address: String) : QwsPrinter?{
        return when (deviceType) {
            DeviceType.X_PRINTER.ordinal -> {
                XPrinter(connType, address)
            }
            DeviceType.G_PRINTER.ordinal -> {
                GPrinter(connType, address)
            }
            else -> {
                null
            }
        }
    }
}